package com.spring.arch.job.service;

import com.spring.arch.job.common.errorcode.JobErrorCode;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.job.model.JobGroup;
import com.spring.arch.job.model.JobInfo;
import com.spring.arch.job.repository.JobGroupRepository;
import com.spring.arch.job.repository.JobInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.spring.arch.job.common.errorcode.JobErrorCode.*;


/**
 * JobInfo实体对应的业务逻辑Service实现类
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class JobInfoService {

    private final JobInfoRepository jobInfoRepository;
	private final JobGroupRepository jobGroupRepository;

    @Autowired
    public JobInfoService(JobInfoRepository jobInfoRepository,
						  JobGroupRepository jobGroupRepository){
        this.jobInfoRepository = jobInfoRepository;
		this.jobGroupRepository = jobGroupRepository;
	}

	/**
	 * 查询任务停止运行的任务信息
	 * @return 任务集合
	 */
	public List<JobInfo> queryAllSuspendJob() {
		return this.jobInfoRepository.findByTriggerStatus(0);
	}

	/**
	 * 创建任务
	 * @param models 任务集合
	 */
	@Transactional
	public List<Integer> saveAll(List<JobInfo> models) {
		List<Integer> jobIds = new ArrayList<>(models.size());
		for (JobInfo job : models) {
			Optional<JobGroup> group = jobGroupRepository.findById(job.getJobGroup());
			if (!group.isPresent()) {
				log.warn("创建任务|任务执行器[{}]不存在", job.getJobGroup());
				throw ExceptionHolder.serviceException(JobErrorCode.E1015001002, String.valueOf(job.getJobGroup()));
			}
			JobInfo info = jobInfoRepository.save(job);
			jobIds.add(info.getId());
		}
		return jobIds;
	}

	/**
	 * 删除任务
	 * @param jobIds 任务ID集合
	 */
	public void deleteAll(List<Integer> jobIds) {
		for (Integer jobId : jobIds) {
			Optional<JobInfo> jobInfo = jobInfoRepository.findById(jobId);
			if (!jobInfo.isPresent()) {
				log.warn("删除任务|任务[{}]不存在", jobId);
				throw ExceptionHolder.serviceException(JobErrorCode.E1015001003, String.valueOf(jobId));
			}
			JobInfo job = jobInfo.get();
			if (1 == job.getTriggerStatus()) {
				log.warn("删除任务|任务[{}]正在执行，不允许删除", jobId);
				throw ExceptionHolder.serviceException(JobErrorCode.E1015001004, String.valueOf(jobId));
			}
			jobInfoRepository.delete(job);
		}
	}

	public void deleteOne(JobInfo job) {
		jobInfoRepository.delete(job);
	}
}
